import React, { Component } from 'react'
import Styles from './index.less'
export default class Tabs extends Component {
  constructor(props) {
      super(props)
      this.menuList = React.Children.map(props.children, v => v.props.tab)
      this.state = {
          currentIndex: 0
      }
      this.menuClick = this.menuClick.bind(this)
  }
  componentWillReceiveProps(nextProps) {
    const { currentIndex } = nextProps
    if (currentIndex && currentIndex !== this.state.currentIndex) {
        this.setState({
            currentIndex
        })
    }
  }
  static TabPane(props) {
      return (
          props.children
      )
  }
  menuClick(index) {
      const { currentIndex } = this.state
      return () => {
          if (currentIndex !== index) {
              this.setState({
                currentIndex: index
              })
          }
      }
  }
  componentDidUpdate(prevProps, prevState) {
    const { onChange } = this.props
    if (!onChange) return
    const { currentIndex } = this.state 
    if (currentIndex!==prevState.currentIndex) {
        onChange(currentIndex)
    }
  }
  render() {
      const { currentIndex } = this.state
      const { children } = this.props
      return (
            <div className={Styles.Tabs}>
                <ul className={Styles.menuList}>
                    {
                        this.menuList.map((v, i) => (
                        <li key={v} onClick={this.menuClick(i)} className={currentIndex === i ? 
                            Styles.active : undefined
                        }>
                            <span>{v}</span>
                        </li>
                        ))
                    }
                </ul>
                {/* <div className={Styles.content} data-content="content">
                    { React.Children.toArray(children).find((v, i) => i === currentIndex) }
                </div>   */}
                {React.Children.map(children, (child, index) => {
                    return (
                        <div data-content="content" className={index === currentIndex ? [Styles.activeTab] : undefined}>
                            {child}
                        </div>
                    )    
                })}
            </div>
        )
    }
}